const dotenv = require("dotenv");
const fs = require("fs");
const path = require("path");

const validEnvs = ["sit", "uat", "ver", "prod"];

const loadEnvConfig = () => {
  const env = process.env.NODE_ENV;

  if (!env || !validEnvs.includes(env)) {
    dotenv.config();
    console.log(`ℹ️  使用默认配置: .env`);
    return {
      env: "default",
      port: process.env.PORT,
      baseUrl: process.env.BASE_URL,
    };
  }

  const envFile = `.env.${env}`;
  if (fs.existsSync(path.resolve(process.cwd(), envFile))) {
    dotenv.config({ path: envFile });
    console.log(`✅ 已加载环境配置文件: ${envFile}`);
  } else {
    console.warn(`⚠️  环境文件 ${envFile} 不存在，回退到默认 .env`);
    dotenv.config();
  }

  return {
    env,
    port: process.env.PORT,
    baseUrl: process.env.BASE_URL,
  };
};

module.exports = { loadEnvConfig };
